package org.atlantis.grosbeak.json;

import java.util.regex.Pattern;

import org.atlantis.grosbeak.castor.Castors;

/**
 * 定制JSON输出的格式。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
public class JsonHandler {

	private int indent;
	private String indentBy;

	// 是否需要压缩
	private boolean compress;

	// 属性名是否需要用双引号（"）括起来
	private boolean quoteName;

	// 是否需要忽略值为null的字段
	private boolean ignoreNull;
	private Pattern actived;
	private Pattern locked;
	private Castors castors;

	public JsonHandler() {
		this(true);
	}

	public JsonHandler(boolean compress) {
		this.compress = compress;
		this.indentBy = "   ";
		this.quoteName = true;
		this.castors = Castors.me();
	}

	public boolean ignore(String name) {
		if (null != actived)
			return !actived.matcher(name).find();
		if (null != locked)
			return locked.matcher(name).find();
		return false;
	}

	public boolean isCompress() {
		return this.compress;
	}

	public JsonHandler setCompress(boolean compress) {
		this.compress = compress;
		return this;
	}

	public int getIndent() {
		return indent;
	}

	public JsonHandler setIndent(int indent) {
		this.indent = indent;
		return this;
	}

	public JsonHandler decreaseIndent() {
		this.indent--;
		return this;
	}

	public JsonHandler increaseIndent() {
		this.indent++;
		return this;
	}

	public String getIndentBy() {
		return indentBy;
	}

	public JsonHandler setIndentBy(String indentBy) {
		this.indentBy = indentBy;
		return this;
	}

	public boolean isQuoteName() {
		return quoteName;
	}

	public JsonHandler setQuoteName(boolean quoteName) {
		this.quoteName = quoteName;
		return this;
	}

	public boolean isIgnoreNull() {
		return this.ignoreNull;
	}

	public JsonHandler setIgnoreNull(boolean ignoreNull) {
		this.ignoreNull = ignoreNull;
		return this;
	}

	public JsonHandler setActived(String regex) {
		this.actived = Pattern.compile(regex);
		return this;
	}

	public JsonHandler setLocked(String regex) {
		this.locked = Pattern.compile(regex);
		return this;
	}

	public Castors getCastors() {
		return castors == null ? Castors.me() : this.castors;
	}

	public JsonHandler setCastors(Castors castors) {
		this.castors = castors;
		return this;
	}

	/**
	 * 压缩，且忽略null值，属性名使用双引号括起来。
	 * 
	 * @return
	 */
	public static JsonHandler compress() {
		return new JsonHandler(true).setIgnoreNull(true);
	}

	/**
	 * 不压缩，且不忽略null值，属性名不使用双引号括起来。
	 * 
	 * @return
	 */
	public static JsonHandler full() {
		return new JsonHandler(false).setIgnoreNull(false).setQuoteName(false);
	}

	/**
	 * 不压缩，忽略null值，属性名不使用双引号括起来。
	 * 
	 * @return
	 */
	public static JsonHandler format() {
		return new JsonHandler(false).setIgnoreNull(true).setQuoteName(false);
	}
}
